package com.tangtanwei.hotel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tangtanwei.hotel.entity.User;
import com.tangtanwei.hotel.entity.bo.CommonConstant;
import com.tangtanwei.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private HttpSession session;

    // 根据账号密码登陆,登陆成功返回用户信息
    @RequestMapping("/login")
    public Object login(@RequestParam(required = false) String username, @RequestParam(required = false)String password){
        if (session.getAttribute(CommonConstant.USER_KEY) != null)
            return "你已登录，不要重复登录！！";

        User one = userService.getOne(new QueryWrapper<User>().eq("name", username).eq("password", password));
        if (one == null){
            return "400";
        }else {
            session.setAttribute(CommonConstant.USER_KEY,one);
            return one;
        }
    }

    // 获得当前登陆用户信息
    @RequestMapping("/getCurrentLoginUser")
    public Object getCurrentLoginUser(HttpServletRequest request){
        return session.getAttribute(CommonConstant.USER_KEY);
    }

    // 查找所有用户
    @RequestMapping("/getAllUser")
    public List<User> getAllUser(){
        return userService.list();
    }

    @RequestMapping("/saveOrupdate")
    public String saveOrUpdateUser(User user){
        return userService.save(user) ? "保存成功": "保存失败";
    }

    //根据用户id删除用户
    @RequestMapping("/delete")
    public String deleteUserById(String id){
        return userService.removeById(id) ? "删除成功": "删除失败";
    }

    // 根据用户名或者电话或者身份证或者生日，搜索用户
    @RequestMapping("/searchUser")
    public List<User> searchUser(String keyword){
        return userService.list(new QueryWrapper<User>().like("name",keyword).or()
                .like("phone",keyword).or().like("idcard",keyword).or().like("birthday",keyword));
    }

    // 注册用户 或者修改用户信息
    @RequestMapping("/register")
    public boolean registerOrUpdate(User user) {
        return userService.saveOrUpdate(user);
    }
}
